<template>
  <div>
    <div id="container"></div>
    <div>
      <el-button type="primary" @click="change2D">切换2D</el-button>
      <el-button type="primary" @click="change3D">切换3D</el-button>
      <el-button type="primary" @click="addMarker">自定义标记</el-button>
    </div>


  </div>

</template>

<style scoped>
#container{

  width: 100%;
  height: 78vh;
}
</style>


<script>
import AMapLoader from '@amap/amap-jsapi-loader';
// eslint-disable-next-line no-unused-vars
import {map} from "core-js/internals/array-iteration";


export default {

  // eslint-disable-next-line vue/multi-word-component-names
  name: "Map",
  data() {
    return {
      map:null,
    }
  },

  created() {
    this.socket();
    this.initMap();
  },
  mounted(){


  },

  methods: {

    addMarker(longitude, latitude) {
      // eslint-disable-next-line no-undef
      const marker = new AMap.Marker ({
        // eslint-disable-next-line no-undef
        position: new AMap.LngLat (longitude, latitude),
        icon: 'logo.png',
        title: '北京'
      });

      this.map.add(marker);
    },

    change3D() {
      // eslint-disable-next-line no-undef
      this.map = new AMap.Map("container",{  //设置地图容器id
        viewMode:"3D",    //是否为3D地图模式
        pitch:50,
        zoom:18,
        center:[116.759946,23.292527],//初始化地图级别
      });
    },

    change2D() {
      // eslint-disable-next-line no-undef
      this.map = new AMap.Map("container",{  //设置地图容器id
        viewMode:"2D",    //是否为3D地图模式
        zoom:18,
        center:[116.759946,23.292527],//初始化地图级别
      });
    },

    initMap(){
      AMapLoader.load({
        key:"3102f64e6e3e58153b9b103025e62021",
        version:"2.0",
        plugins:['AMap.MapType','AMap.ToolBar'],
      }).then((AMap)=>{
        this.map = new AMap.Map("container",{
          viewMode:"2D",
          zoom:18,
          center:[116.759946,23.292527],
        });
        this.map.addControl(new AMap.MapType());
        this.map.addControl(new AMap.ToolBar());
        this.addMarker(116.759946,23.292527)
      }).catch(e=>{
        console.log(e);
      })

    },

    handleMessage(message) {
      const lng = JSON.parse(message).lng;
      const lat = JSON.parse(message).lat;
      this.addMarker(lng,lat);
      console.log('收到WebSocket消息:', message);

    },
    socket(){
      this.$options.sockets.onopen = () => {
        console.log('WebSocket连接已打开');
      };

      this.$options.sockets.onmessage = (event) => {
        this.handleMessage(event.data);
        console.log('收到WebSocket消息:', event.data);
      };

      this.$options.sockets.onerror = (event) => {
        console.error('WebSocket错误:', event);
      };

      // eslint-disable-next-line no-unused-vars
      this.$options.sockets.onclose = (event) => {
        console.log('WebSocket连接已关闭');
      };
    }
  }
}

</script>

<style scoped>

</style>